package top.infopub.job.quartz.init;


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import top.infopub.zookeeper.EvnUtils;


/**
 * 从zk加载配置
 * @author Awoke
 * @version 2018年10月9日
 * @see InitPropertiesListener
 * @since
 */
public class InitPropertiesListener implements ServletContextListener {

    private static final Logger log = LoggerFactory.getLogger(InitPropertiesListener.class);

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {}

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        OutputStream fos = null;
        try {
            String profilepath = InitPropertiesListener.class.getResource("/").getPath()
                                 + "quartz.properties";
            Properties props = new Properties();
            props.load(new FileInputStream(profilepath));
            fos = new FileOutputStream(profilepath);
            // Using datasource
            props.setProperty("org.quartz.jobStore.dataSource", "qzDS");
            // Define the datasource to use
            props.setProperty("org.quartz.dataSource.qzDS.driver", "oracle.jdbc.OracleDriver");
            props.setProperty("org.quartz.dataSource.qzDS.validationQuery", "select 1 from dual");
            props.setProperty("org.quartz.dataSource.qzDS.URL", EvnUtils.getValue("jdbc.url"));
            props.setProperty("org.quartz.dataSource.qzDS.user",
                EvnUtils.getValue("jdbc.username"));
            props.setProperty("org.quartz.dataSource.qzDS.password",
                EvnUtils.getValue("jdbc.password"));
            props.setProperty("org.quartz.dataSource.qzDS.maxConnections",
                EvnUtils.getValue("ds.maxActive"));
            props.store(fos, "init quartz.properties from zk");
            fos.flush();

            log.info(" init quartz.properties from zk successfully ---");
        }
        catch (Exception e) {
            log.error(" init quartz.properties error", e);
        }
        finally {
            IOUtils.closeQuietly(fos);
        }
    }

}
